package com.xforceplus.bsstool.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.xforceplus.bsstool.db.NewUcenterDB;
import com.xforceplus.bsstool.db.OldUcenterDB;
import com.xforceplus.bsstool.log.LogMain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServiceStep8 {

  /**
   * 获取老运营用户列表
   * @return
   */
  public static List<Map> getOldUserList(Long tenantId,LogMain logger) throws Exception {
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_user t where t.group_id = ").append(tenantId);
    logger.info("执行老运营用户获取，执行SQL: "+sql.toString());
    return OldUcenterDB.getSqlResult(sql.toString());
  }
  /**
   * 获取新运营用户列表
   * @return
   */
  public static Map<String,Map> getNewUserMap(Long tenantId,LogMain logger) throws Exception {
    Map<String,Map> newUserMapMap  = new HashMap<>();
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_user t where t.tenant_id = ").append(tenantId);
    logger.info("执行新运营用户获取，执行SQL: "+sql.toString());
    List<Map> newUserList = NewUcenterDB.getSqlResult(sql.toString());
    for (Map newUserMap : newUserList){
      newUserMapMap.put(String.valueOf(newUserMap.get("user_id")),newUserMap);
    }
    return newUserMapMap;
  }

  /**
   * 比对新运营用户列表
   * @return
   */
  public static boolean compareUserWithNew(List<Map> oldUserList,Long tenantId,LogMain logger) throws Exception {
    boolean result = true;
    Map<String,Map> newUserMapMap  = getNewUserMap(tenantId,logger);
    for (Map oldUserMap : oldUserList){
      System.out.println("开始执行用户比对 用户ID:"+oldUserMap.get("user_id"));
      logger.info("开始执行用户比对 用户ID:"+oldUserMap.get("user_id"));
      //查询新运营对应功能集
      Map newUserMap =newUserMapMap.get(String.valueOf(oldUserMap.get("user_id")));
      if (newUserMap == null){
        logger.warn("用户ID:"+oldUserMap.get("user_id")+" 等待迁移中...");
      }else {
        logger.info("新老运营存在相同用户ID,继续执行数据信息比对 新运营用户："+ JSON.toJSONString(newUserMap));
        //新老数据比对： tenant_id account_id  user_name user_phone
        // user_email_addr active_status status invoice_type
        oldUserMap.put("tenant_id",oldUserMap.get("group_id"));
        result = ServiceCommon.compareMapValue(oldUserMap,newUserMap,
                Lists.newArrayList("tenant_id","account_id","user_name","user_phone",
                        "user_email_addr","active_status","status","invoice_type"),
                "用户ID:"+oldUserMap.get("user_id"),
                logger);
        //如果用户绑定账户ID为0,则报错
        if ("0".equals(oldUserMap.get("account_id"))){
          logger.error("老运营用户ID:"+oldUserMap.get("user_id")+ " 检测到绑定的account_id为0！");
        }
      }

      //重复用户检查
      List<Map> sameUserList = null;
      if (StringUtils.isNotBlank((String)oldUserMap.get("user_phone"))) {
        String userPhone = (String)oldUserMap.get("user_phone");
        if (userPhone.contains("\'")){
          userPhone = userPhone.replaceAll("\'","");
        }

        NewUcenterDB.getSqlResult("select * from sys_user where user_id != " + oldUserMap.get("user_id")
                + " and tenant_id = " + oldUserMap.get("group_id")
                + " and user_phone = '" + userPhone + "'");
        if (!CollectionUtils.isEmpty(sameUserList)) {
          logger.error("老运营用户ID:" + oldUserMap.get("user_id") + " 新运营存在重复用户(user_phone重复)记录个数：" + JSON.toJSONString(sameUserList));
          result = false;
        }
      }
      if (StringUtils.isNotBlank((String)oldUserMap.get("user_email_addr"))) {
        String userEmailAddr = (String)oldUserMap.get("user_email_addr");
        if (userEmailAddr.contains("\'")){
          userEmailAddr = userEmailAddr.replaceAll("\'","");
        }
        NewUcenterDB.getSqlResult("select * from sys_user where user_id != " + oldUserMap.get("user_id")
                + " and tenant_id = " + oldUserMap.get("group_id")
                + " and user_email_addr = '" + userEmailAddr + "'");
        if (!CollectionUtils.isEmpty(sameUserList)) {
          logger.error("老运营用户ID:" + oldUserMap.get("user_id") + " 新运营存在重复用户(user_email_addr重复)记录个数：" + JSON.toJSONString(sameUserList));
          result = false;
        }
      }
    }
    return result;
  }


  /**
   * 获取老运营角色人员关系列表
   * @return
   */
  public static List<Map> getOldRoleUserRelList(Long tenantId,Long userId,LogMain logger) throws Exception {
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_role_user_rel t where t.group_id = ")
            .append(tenantId).append(" and user_id =").append(userId);
    logger.info("执行老运营角色人员关系获取，执行SQL: "+sql.toString());
    return OldUcenterDB.getSqlResult(sql.toString());
  }
  /**
   * 获取新运营角色人员关系列表
   * @return
   */
  public static Map<String,Map> getNewRoleUserRelMap(Long tenantId,Long userId,LogMain logger) throws Exception {
    Map<String,Map> newRoleUserRelMapMap  = new HashMap<>();
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_role_user_rel t where t.tenant_id = ")
            .append(tenantId).append(" and user_id =").append(userId);
    logger.info("执行新运营角色人员关系获取，执行SQL: "+sql.toString());
    List<Map> newRoleUserRelList = NewUcenterDB.getSqlResult(sql.toString());
    for (Map newRoleUserRelMap : newRoleUserRelList){
      newRoleUserRelMapMap.put(String.valueOf(newRoleUserRelMap.get("id")),newRoleUserRelMap);
    }
    return newRoleUserRelMapMap;
  }

  /**
   * 比对新运营角色人员关系列表
   * @return
   */
  public static boolean compareRoleUserRelWithNew(List<Map> oldRoleUserRelList,Long tenantId,Long userId,LogMain logger) throws Exception {
    boolean result = true;
    Map<String,Map> newRoleUserRelMapMap  = getNewRoleUserRelMap(tenantId,userId,logger);
    for (Map oldRoleUserRelMap : oldRoleUserRelList){
      System.out.println("开始执行角色人员关系比对 角色人员关系ID:"+oldRoleUserRelMap.get("id"));
      logger.info("开始执行角色人员关系比对 角色人员关系ID:"+oldRoleUserRelMap.get("id"));
      //查询新运营对应功能集
      Map newRoleUserRelMap =newRoleUserRelMapMap.get(String.valueOf(oldRoleUserRelMap.get("id")));
      if (newRoleUserRelMap == null){
        logger.warn("角色人员关系ID:"+oldRoleUserRelMap.get("id")+" 等待迁移中...");
      }else {
        logger.info("新老运营存在相同角色人员关系ID,继续执行数据信息比对 新运营角色人员关系："+ JSON.toJSONString(newRoleUserRelMap));
        //新老数据比对： tenant_id role_id user_id
        oldRoleUserRelMap.put("tenant_id",oldRoleUserRelMap.get("group_id"));
        result = ServiceCommon.compareMapValue(oldRoleUserRelMap,newRoleUserRelMap,
                Lists.newArrayList("tenant_id","role_id","user_id"),
                "角色人员关系ID:"+oldRoleUserRelMap.get("id"),
                logger);
      }

      //重复角色人员关系检查
      List<Map> sameRoleUserRelList = NewUcenterDB.getSqlResult("select * from sys_role_user_rel where id != "+oldRoleUserRelMap.get("id")
              +" and tenant_id = "+oldRoleUserRelMap.get("group_id")
              +" and user_id = "+oldRoleUserRelMap.get("user_id")
              +" and role_id = "+oldRoleUserRelMap.get("role_id"));
      if (!CollectionUtils.isEmpty(sameRoleUserRelList)){
        logger.error("老运营角色人员关系ID:"+oldRoleUserRelMap.get("id")+" 新运营存在重复角色人员关系记录个数："+sameRoleUserRelList.size());
        result = false;
      }
    }
    return result;
  }



  /**
   * 获取老运营账户列表
   * @return
   */
  public static List<Map> getOldSassAccountList(Long accountId,LogMain logger) throws Exception {
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_sass_account t where t.account_id = ").append(accountId);
    logger.info("执行老运营账户获取，执行SQL: "+sql.toString());
    return OldUcenterDB.getSqlResult(sql.toString());
  }
  /**
   * 获取新运营账户列表
   * @return
   */
  public static Map<String,Map> getNewSassAccountMap(Long accountId,LogMain logger) throws Exception {
    Map<String,Map> newSassAccountMapMap  = new HashMap<>();
    StringBuilder sql = new StringBuilder();
    sql.append("select * from sys_sass_account t where t.account_id = ").append(accountId);
    logger.info("执行新运营账户获取，执行SQL: "+sql.toString());
    List<Map> newSassAccountList = NewUcenterDB.getSqlResult(sql.toString());
    for (Map newSassAccountMap : newSassAccountList){
      newSassAccountMapMap.put(String.valueOf(newSassAccountMap.get("account_id")),newSassAccountMap);
    }
    return newSassAccountMapMap;
  }

  /**
   * 比对新运营账户列表
   * @return
   */
  public static boolean compareSassAccountWithNew(List<Map> oldSassAccountList,Long accountId,LogMain logger) throws Exception {
    boolean result = true;
    Map<String,Map> newSassAccountMapMap  = getNewSassAccountMap(accountId,logger);
    for (Map oldSassAccountMap : oldSassAccountList){
      System.out.println("开始执行账户比对 账户ID:"+oldSassAccountMap.get("account_id"));
      logger.info("开始执行账户比对 账户ID:"+oldSassAccountMap.get("account_id"));
      //查询新运营对应功能集
      Map newSassAccountMap =newSassAccountMapMap.get(String.valueOf(oldSassAccountMap.get("account_id")));
      if (newSassAccountMap == null){
        logger.warn("账户ID:"+oldSassAccountMap.get("account_id")+" 等待迁移中...");
      }else {
        logger.info("新老运营存在相同账户ID,继续执行数据信息比对 新运营账户："+ JSON.toJSONString(newSassAccountMap));
        //新老数据比对： email password tel_phone status
        result = ServiceCommon.compareMapValue(oldSassAccountMap,newSassAccountMap,
                Lists.newArrayList("email","password","tel_phone","status"),
                "账户ID:"+oldSassAccountMap.get("account_id"),
                logger);
      }

      //重复账户检查
      List<Map> sameSassAccountList = null;
      if (StringUtils.isNotBlank(String.valueOf(oldSassAccountMap.get("email")))) {
        String email = (String)oldSassAccountMap.get("email");
        if (email.contains("\'")){
          email = email.replaceAll("\'","");
        }

        NewUcenterDB.getSqlResult("select * from sys_sass_account where account_id != " + oldSassAccountMap.get("account_id")
                + " and email = '" + email + "'");
        if (!CollectionUtils.isEmpty(sameSassAccountList)) {
          logger.error("老运营账户ID:" + oldSassAccountMap.get("account_id") + " 新运营存在重复账户(email重复)记录个数：" + sameSassAccountList.size());
          result = false;
        }
      }
      if (StringUtils.isNotBlank(String.valueOf(oldSassAccountMap.get("tel_phone")))) {
        String telPhone = (String)oldSassAccountMap.get("tel_phone");
        if (telPhone.contains("\'")){
          telPhone = telPhone.replaceAll("\'","");
        }
        sameSassAccountList = NewUcenterDB.getSqlResult("select * from sys_sass_account where account_id != " + oldSassAccountMap.get("account_id")
                + " and tel_phone = '" + telPhone + "'");
        if (!CollectionUtils.isEmpty(sameSassAccountList)) {
          logger.error("老运营账户ID:" + oldSassAccountMap.get("account_id") + " 新运营存在重复账户(tel_phone重复)记录个数：" + sameSassAccountList.size());
          result = false;
        }
      }
    }
    return result;
  }
}
